<template>
  <BaseDialog
    ref="baseDialogRef"
    v-bind="props"
    :dialogTitle="dialogTitle"
    @dialogClosed="closed"
    @dialogSubmit="dialogSubmit"
  >
    <template #dialog_body>
      <!--查询组件-->
      <TableQueryComponent
        v-model:queryForm="query"
        :loadTableList="loadTableList"
        :removeQueryField="removeQueryField"
        :clearQuery="clearQuery"
        :queryFormHeaders="queryFormHeaders"
        :showResetButton="false"
        :autoSubmit="true"
      ></TableQueryComponent>
      <!--工具栏-->
      <div style="margin-bottom: 10px">
        <el-button icon="Plus" type="primary" class="button" @click="addRow">上传新图片</el-button>
      </div>
      <!--图片列表-->
      <el-checkbox-group v-model="checkSelect">
        <el-row :gutter="10">
          <el-col :span="4" v-for="item in table.data" :key="item.id">
            <div>
              <PictureComponent
                pictureWidth="100%"
                pictureHeight="120px"
                :picUrl="item.fileHttpUrl"
                :addBorder="true"
              />
              <div class="picture_name">
                <el-checkbox :label="item.title" :value="item.id" />
              </div>
            </div>
          </el-col>
        </el-row>
      </el-checkbox-group>
      <!--分页插件-->
      <TablePagination
        v-bind="table"
        :changePageSize="changePageSize"
        :changePage="changePage"
        :pageSizes="[12, 18, 24, 36, 48]"
        :defaultPageSize="18"
      />
    </template>
  </BaseDialog>
  <!-- 图片上传表单 -->
  <PhotoUploadDialog
    ref="photoUploadDialogRef"
    title="图片资源上传"
    :data="{ dirName: 'image' }"
    :autoUpload="false"
    :limit="5"
    @uploadSuccess="uploadImgSuccess"
  />
</template>

<script lang="ts" setup>
// 导入表格查询组件
import TableQueryComponent from '@/components/base/table/TableQueryComponent.vue';
// 导入分页插件
import TablePagination from '@/components/base/table/TablePagination.vue';
// 导入上传图像组件
import PhotoUploadDialog from '@/components/base/dialog/PhotoUploadDialogComponent.vue';
import BaseDialog from '@/components/base/dialog/BaseDialogComponent.vue';
import PictureComponent from '@/components/base/other/PictureComponent.vue';
import useTableList from '@/api/hooks/useTableList';
import urls from '@/api/request/urls';

import { computed, nextTick, provide, ref, watch } from 'vue';
import { defineEmits } from 'vue';
import type { FormHeader } from '@/types/interface/base_interface';
import { ElMessage } from 'element-plus';

// 表格工具必备参数
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(
  urls.API_URL_BACKSTAGE_FILERESOURCE_MANAGE,
  true,
  { resourceType: 'image' },
  false
);
//将每页数量改为18
changePageSize(18);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);
const emit = defineEmits(['afterSubmit']);

// 接收父组件的值
interface Props {
  dialogWidth?: string; // 对话框宽度
  dialogTitle?: string; // 对话框标题,前台传入，不用加入添加或编辑的文本。添加或编辑的文本由action属性决定
  showDialogFoot?: Boolean; // 是否显示对话框脚部
  multiple?: Boolean; // 是否多选。默认不多选
  multipleLimit?: number; //multiple 属性设置为 true 时，代表多选场景下用户最多可以选择的项目数， 为 0 则不限制
  limit?: number; // 允许选择的最大数量
  autoUpload?: boolean; // 是否自动上传
  data?: Record<string, any>; // 上传时附带的额外参数
}
const props = withDefaults(defineProps<Props>(), {
  dialogTitle: '图片上传',
  dialogWidth: '1000px',
  multiple: () => Boolean(false),
  multipleLimit: 1,
  autoUpload: true
});

const checkSelect = ref<string[]>([]);
//监听复选框选择变动
watch(
  () => checkSelect,
  (newVal: any, oldVal: any) => {
    // console.log(newVal);
  },
  { deep: true, immediate: true }
);
//对话框对象
const baseDialogRef = ref();
const action = ref<string>('');
// 打开此对话框的函数
const openDialog = async (url: string) => {
  //重新加载数据
  loadTableList();
  await nextTick();
  baseDialogRef.value.openDialog();
};
// 关闭此对话框的函数
const closeDialog = () => {
  baseDialogRef.value.closeDialog();
};
const closed = () => {
  // 清空选择的图片信息
  checkSelect.value = [];
};
//对话框提交事件
const dialogSubmit = () => {
  let valid = true; //验证是否符合提交要求，默认符合
  if (checkSelect.value.length == 0) {
    valid = false;
    ElMessage.error('请选择图片');
  }
  if (props.multiple && props.multipleLimit > 1) {
    //如果是多选并且限制大于1
    if (checkSelect.value.length > props.multipleLimit) {
      valid = false;
      ElMessage.error(`最多只能选择${props.multipleLimit}张图片`);
    }
  } else {
    //如果只能选择一个
    if (checkSelect.value.length > 1) {
      valid = false;
      ElMessage.error(`最多只能选择1张图片`);
    }
  }
  //如果符合提交规则
  if (valid) {
    emit('afterSubmit', checkSelect.value);
    baseDialogRef.value.closeDialog();
  }
};
//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([
  // 查询表单
  {
    prop: 'title',
    label: '标题'
  }
]);
//上传图片==========================================================
// 上传组件================================
const photoUploadDialogRef = ref();
//当点击新增图片资源时
const addRow = () => {
  // 设置上传地址
  let uploadImgUrl = urls.API_URL_BACKSTAGE_FILERESOURCE_UPLOAD;
  photoUploadDialogRef.value.openDialog(uploadImgUrl);
};
// 当上传成功
const uploadImgSuccess = () => {
  // 重新加载表格
  loadTableList();
};

defineExpose({
  // 参考vue3官方文档，需要将函数暴露出去才能被父组件调用，setup模式是不暴露的
  openDialog,
  closeDialog
});
</script>

<style lang="scss" scoped>
.photo-upload-dialog {
  .el-upload__tip {
    text-align: center;
  }
}
div.picture_name {
  overflow: hidden; /* 隐藏超出部分的文本 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  white-space: nowrap; /* 文本不换行 */
  text-align: center;
}
</style>
